<?php

require_once('pownce.class.php');
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();

// Load form data
$pownce_username = $_POST['pownce_username'];
$pownce_password = $_POST['pownce_password'];
$pownce_filter = $_POST['pownce_filter'];

// Initiate Pownce object
$pownce = new Pownce($pownce_username, $pownce_password, "c7wccp874bxu420ao7e01m8s55q5ib0y"); // My API Key...will be useless in 7 days

// Get the user's notes
$pownce->getUserNotes($pownce_username, "json");
$pownce->addOption("limit", "100");
$pownce->addOption("filter", $pownce_filter);
$notes = json_decode($pownce->execute())->{'notes'};

// Low-rent counter for nice table look
$current_row_count = 1;

// Cheap way to note if any files were written
$num_bytes_written = 0;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Pownce export tool</title>

  <!-- Framework CSS -->
  <link rel="stylesheet" href="./blueprint/screen.css" type="text/css" media="screen, projection">
  <link rel="stylesheet" href="./blueprint/print.css" type="text/css" media="print">
  <!--[if IE]><link rel="stylesheet" href="./blueprint/ie.css" type="text/css" media="screen, projection"><![endif]-->
</head>
<body>

  <div class="container">  
    <h1>Pownce export tool</h1>
    <hr>

    <table border="0" cellspacing="0" cellpadding="0"> 
      <tr> 
        <th class="span-3">ID</th> 
        <th class="span-6">Date</th> 
        <th class="span-3">Link</th> 
        <th class="span-12">Description</th> 
      </tr> 
		<?php foreach ($notes as $note) { 
			if (!is_null($note->{"file"})) {
				// Get basic note fields
				$note_id = $note->{'id'};
				$note_timestamp = date('Y-m-d_His', $note->{'timestamp'});
				$note_url = $note->{'file'}->{'direct_url'};
				$note_filename = $note_timestamp.'_'.$note->{'file'}->{'name'};
				$note_body = $note->{'body'};
				
				// Download and save file
				$client = new Zend_Http_Client($note_url); 
				$response = $client->request();
				$num_bytes_written = file_put_contents($note_filename, $response->getRawBody());

				// Write table row...this is terrible code and I need to use Smarty
				if ($current_row_count % 2 == 0)
					echo "<tr class='even'>";
				else
					echo "<tr>";
					
				echo "<td>$note_id</td><td>$note_timestamp</td><td><a href='$note_url'>Link</a></td><td>$note_body</td></tr>";
				
				$current_row_count++;
			}			
		}
		?>
	</table>
	
	<?php
	if ($num_bytes_written > 0)
		echo "<div class='success'><strong>Congratulations!</strong> The above files have been saved to the current directory.</div>";
	else
		echo "<div class='error'><strong>Uh oh!</strong> It doesn't seem like any files were saved.</div>";
	?>	
	<hr>
	
	<p class="box">&copy; 2008 Ross Belmont</p>

  </div>
</body>
</html>